<template>
  <div class="dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>数据概览</h1>
      <p>医院管理系统运营数据总览</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :xs="12" :sm="8" :lg="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon primary">
              <el-icon size="24"><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalUsers }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
          <div class="stat-trend">
            <span class="trend-up">+{{ stats.newUsersToday }}</span>
            <span class="trend-text">今日新增</span>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="8" :lg="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon success">
              <el-icon size="24"><Avatar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalDoctors }}</div>
              <div class="stat-label">在职医生</div>
            </div>
          </div>
          <div class="stat-trend">
            <span class="trend-stable">{{ stats.activeDoctors }}</span>
            <span class="trend-text">今日在岗</span>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="8" :lg="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon warning">
              <el-icon size="24"><Tickets /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.todayRegistrations }}</div>
              <div class="stat-label">今日挂号</div>
            </div>
          </div>
          <div class="stat-trend">
            <span class="trend-up">+{{ stats.registrationGrowth }}%</span>
            <span class="trend-text">较昨日</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 挂号趋势图 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>挂号趋势</span>
              <el-select v-model="registrationPeriod" size="small" style="width: 100px">
                <el-option label="7天" value="7d" />
                <el-option label="30天" value="30d" />
                <el-option label="90天" value="90d" />
              </el-select>
            </div>
          </template>
          <div ref="registrationChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 科室分布图 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>科室就诊分布</span>
              <el-button size="small" type="text" @click="refreshDepartmentChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div ref="departmentChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时数据和预警 -->
    <el-row :gutter="20" class="real-time-section">
      <!-- 实时挂号 -->
      <el-col :xs="24" :lg="12">
        <el-card class="real-time-card">
          <template #header>
            <div class="card-header">
              <span>实时挂号</span>
              <el-badge :value="realtimeRegistrations.length" type="primary">
                <el-icon><Bell /></el-icon>
              </el-badge>
            </div>
          </template>
          <div class="real-time-list">
            <div
              v-for="item in realtimeRegistrations"
              :key="item.id"
              class="real-time-item"
            >
              <div class="item-info">
                <div class="item-title">{{ item.patientName }}</div>
                <div class="item-desc">{{ item.doctorName }} · {{ item.departmentName }}</div>
              </div>
              <div class="item-time">{{ item.time }}</div>
            </div>
            <div v-if="realtimeRegistrations.length === 0" class="empty-state">
              <el-icon size="48" color="#c0c4cc"><DocumentRemove /></el-icon>
              <p>暂无实时挂号数据</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 系统预警 -->
      <el-col :xs="24" :lg="12">
        <el-card class="warning-card">
          <template #header>
            <div class="card-header">
              <span>系统预警</span>
              <el-badge :value="warnings.length" type="danger">
                <el-icon><Warning /></el-icon>
              </el-badge>
            </div>
          </template>
          <div class="warning-list">
            <el-alert
              v-for="warning in warnings"
              :key="warning.id"
              :title="warning.title"
              :description="warning.description"
              :type="warning.type"
              :closable="false"
              show-icon
              class="warning-item"
            />
            <div v-if="warnings.length === 0" class="empty-state">
              <el-icon size="48" color="#67c23a"><SuccessFilled /></el-icon>
              <p>系统运行正常</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速操作 -->
    <el-card class="quick-actions">
      <template #header>
        <span>快速操作</span>
      </template>
      <div class="actions-grid">
        <div class="action-item" @click="navigateTo('/users')">
          <el-icon size="32" color="#409eff"><User /></el-icon>
          <span>用户管理</span>
        </div>
        <div class="action-item" @click="navigateTo('/doctors')">
          <el-icon size="32" color="#67c23a"><Avatar /></el-icon>
          <span>医生管理</span>
        </div>
        <div class="action-item" @click="navigateTo('/registrations')">
          <el-icon size="32" color="#e6a23c"><Tickets /></el-icon>
          <span>挂号管理</span>
        </div>
        <div class="action-item" @click="navigateTo('/medicines')">
          <el-icon size="32" color="#f56c6c"><FirstAidKit /></el-icon>
          <span>药品管理</span>
        </div>
        <div class="action-item" @click="navigateTo('/schedules')">
          <el-icon size="32" color="#909399"><Calendar /></el-icon>
          <span>排班管理</span>
        </div>
        <div class="action-item" @click="navigateTo('/announcements')">
          <el-icon size="32" color="#409eff"><Bell /></el-icon>
          <span>公告管理</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import {
  getDashboardStatistics,
  getRegistrationTrend,
  getDepartmentDistribution,
  getRealtimeRegistrations,
  getSystemWarnings
} from '../api/admin'

const router = useRouter()

// 图表引用
const registrationChartRef = ref(null)
const departmentChartRef = ref(null)
let registrationChart = null
let departmentChart = null

// 统计数据
const stats = reactive({
  totalUsers: 0,
  newUsersToday: 0,
  totalDoctors: 0,
  activeDoctors: 0,
  todayRegistrations: 0,
  registrationGrowth: 0
})

// 挂号趋势周期
const registrationPeriod = ref('7d')

// 实时挂号数据
const realtimeRegistrations = ref([])

// 系统预警
const warnings = ref([])

// 加载统计数据
const loadStatistics = async () => {
  try {
    const { data } = await getDashboardStatistics()
    Object.assign(stats, data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  }
}

// 加载挂号趋势数据
const loadRegistrationTrend = async () => {
  try {
    const days = parseInt(registrationPeriod.value)
    const { data } = await getRegistrationTrend(days)
    updateRegistrationChart(data)
  } catch (error) {
    console.error('加载挂号趋势数据失败:', error)
    ElMessage.error('加载挂号趋势数据失败')
  }
}

// 加载科室分布数据
const loadDepartmentDistribution = async () => {
  try {
    const { data } = await getDepartmentDistribution()
    updateDepartmentChart(data)
  } catch (error) {
    console.error('加载科室分布数据失败:', error)
    ElMessage.error('加载科室分布数据失败')
  }
}

// 加载实时挂号数据
const loadRealtimeRegistrations = async () => {
  try {
    const { data } = await getRealtimeRegistrations()
    realtimeRegistrations.value = data
  } catch (error) {
    console.error('加载实时挂号数据失败:', error)
  }
}

// 加载系统预警
const loadWarnings = async () => {
  try {
    const { data } = await getSystemWarnings()
    warnings.value = data
  } catch (error) {
    console.error('加载系统预警失败:', error)
  }
}

// 初始化挂号趋势图
const initRegistrationChart = () => {
  if (!registrationChartRef.value) return
  
  registrationChart = echarts.init(registrationChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '挂号数量',
        type: 'line',
        smooth: true,
        data: [],
        itemStyle: {
          color: '#409eff'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        }
      }
    ]
  }
  
  registrationChart.setOption(option)
}

// 更新挂号趋势图数据
const updateRegistrationChart = (data) => {
  if (!registrationChart) return
  
  registrationChart.setOption({
    xAxis: {
      data: data.dates
    },
    series: [
      {
        data: data.counts
      }
    ]
  })
}

// 初始化科室分布图
const initDepartmentChart = () => {
  if (!departmentChartRef.value) return
  
  departmentChart = echarts.init(departmentChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '就诊人数',
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  departmentChart.setOption(option)
}

// 更新科室分布图数据
const updateDepartmentChart = (data) => {
  if (!departmentChart) return
  
  departmentChart.setOption({
    series: [
      {
        data: data
      }
    ]
  })
}

// 刷新科室图表
const refreshDepartmentChart = async () => {
  await loadDepartmentDistribution()
}

// 导航到指定页面
const navigateTo = (path) => {
  router.push(path)
}

// 监听挂号周期变化
watch(registrationPeriod, () => {
  loadRegistrationTrend()
})

// 设置图表响应式
const handleResize = () => {
  registrationChart?.resize()
  departmentChart?.resize()
}

// 初始化数据
const initData = async () => {
  await Promise.all([
    loadStatistics(),
    loadRegistrationTrend(),
    loadDepartmentDistribution(),
    loadRealtimeRegistrations(),
    loadWarnings()
  ])
}

// 定时刷新数据
const startDataRefresh = () => {
  // 每分钟刷新一次统计数据
  setInterval(async () => {
    await loadStatistics()
  }, 60000)

  // 每30秒刷新一次实时挂号数据
  setInterval(async () => {
    await loadRealtimeRegistrations()
  }, 30000)

  // 每5分钟刷新一次预警信息
  setInterval(async () => {
    await loadWarnings()
  }, 300000)
}

onMounted(() => {
  nextTick(() => {
    initRegistrationChart()
    initDepartmentChart()
    initData()
    startDataRefresh()
    
    window.addEventListener('resize', handleResize)
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  registrationChart?.dispose()
  departmentChart?.dispose()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  height: 120px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-icon.primary {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.stat-icon.success {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.stat-icon.warning {
  background-color: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
}

.stat-icon.danger {
  background-color: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.trend-up {
  color: #67c23a;
  font-weight: 500;
}

.trend-stable {
  color: #409eff;
  font-weight: 500;
}

.trend-text {
  color: #909399;
}

.charts-section {
  margin-bottom: 24px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 320px;
}

.real-time-section {
  margin-bottom: 24px;
}

.real-time-card,
.warning-card {
  height: 400px;
}

.real-time-list,
.warning-list {
  height: 320px;
  overflow-y: auto;
}

.real-time-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.real-time-item:last-child {
  border-bottom: none;
}

.item-info {
  flex: 1;
}

.item-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.item-desc {
  font-size: 12px;
  color: #909399;
}

.item-time {
  font-size: 12px;
  color: #606266;
}

.warning-item {
  margin-bottom: 12px;
}

.warning-item:last-child {
  margin-bottom: 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.empty-state p {
  margin: 8px 0 0 0;
  font-size: 14px;
}

.quick-actions {
  margin-bottom: 24px;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
  transform: translateY(-2px);
}

.action-item span {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards .el-col {
    margin-bottom: 16px;
  }
  
  .charts-section .el-col,
  .real-time-section .el-col {
    margin-bottom: 16px;
  }
  
  .actions-grid {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .action-item {
    padding: 16px 8px;
  }
}

@media (max-width: 480px) {
  .actions-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style> 